import {
  Body,
  Controller,
  Delete,
  Get,
  Headers,
  HttpException,
  HttpStatus,
  Param,
  ParseIntPipe,
  Post,
  Put,
  Query,
  Redirect,
  Render,
  Res,
  UseFilters,
} from '@nestjs/common';
import { UserService } from '../../shared/services/user.service';
import { ApiCookieAuth, ApiTags } from '@nestjs/swagger';
import { CreateUserDto, UpdateUserDto } from 'src/shared/dtos/user.dto';
import { AdminException } from '../filters/admin-exception';
import { UtilityService } from '../../shared/services/utility.service';
import { Result } from '../../shared/vo/result';
import type { Response } from 'express';
import { ParseOptionalIntPipe } from 'src/shared/pipes/parse-optional-int.pipe';

@UseFilters(AdminException)
@Controller('admin/users')
@ApiTags('admin/user')
export class UserController {
  constructor(
    private readonly userService: UserService,
    private readonly utilityService: UtilityService,
  ) {}

  @Get()
  @Render('user/user-list')
  async findAll(
    @Query('keyword') keyword: string = '',
    @Query('page', new ParseOptionalIntPipe(1)) page: number,
    @Query('limit', new ParseOptionalIntPipe(1)) limit: number,
  ) {
    const { users, total } = await this.userService.findAllWithPagination(
      page,
      limit,
      keyword,
    );
    const pageCount = Math.ceil(total / limit);
    return {
      users,
      keyword,
      total,
      pageCount,
      page,
      limit,
    };
  }

  @Get('create')
  @Render('user/user-form')
  createForm() {
    return { user: {} };
  }

  @Post()
  @Redirect('/admin/users') // 创建完成后跳转到用户列表页
  async create(@Body() createUserDto: CreateUserDto) {
    if (createUserDto.password) {
      // Hash加密
      createUserDto.password = await this.utilityService.hashPassword(
        createUserDto.password,
      );
    }
    await this.userService.create(createUserDto);
    return { success: true };
  }

  @Get(':id/edit')
  @Render('user/user-form')
  async editForm(@Param('id', ParseIntPipe) id: number) {
    const user = await this.userService.findOne({ where: { id } });
    if (!user)
      throw new HttpException('User not found', HttpStatus.BAD_REQUEST);
    return { user };
  }

  @Put(':id')
  // @Redirect('/admin/users') // 创建完成后跳转到用户列表页
  async update(
    @Param('id', ParseIntPipe) id: number,
    @Body() updateUserDto: UpdateUserDto,
    @Res({ passthrough: true }) res: Response,
    @Headers('accept') accept: string,
  ) {
    if (updateUserDto.password) {
      // Hash加密
      updateUserDto.password = await this.utilityService.hashPassword(
        updateUserDto.password,
      );
    } else {
      delete updateUserDto.password;
    }
    await this.userService.update(id, updateUserDto);
    if (accept.includes('application/json')) {
      // 如果有@Res(),就只能自己返回json；
      // 如果想直接返回Result.ok(null)，就得写成@Res({ passthrough: true }) res: Response,
      return res.json(Result.ok(null));
    } else {
      res.redirect('/admin/users');
    }
  }

  @Delete(':id')
  async delete(@Param('id', ParseIntPipe) id: number) {
    const res = await this.userService.delete(id);
    if (res.affected) {
      return Result.ok(null);
    } else {
      throw new HttpException('用户未找到', HttpStatus.NOT_FOUND);
    }
  }

  @Get(':id')
  @Render('user/user-detail')
  async detail(@Param('id', ParseIntPipe) id: number) {
    const user = await this.userService.findOne({ where: { id } });
    if (!user)
      throw new HttpException('User not found', HttpStatus.BAD_REQUEST);
    return { user };
  }
}
